package com.xm.settlement.service.impl;

import com.xm.settlement.commons.utils.RedisBeanUtils;
import com.xm.settlement.model.AppBase;
import com.xm.settlement.model.vo.UserExpansionVo;
import com.xm.settlement.service.IAppBaseService;
import com.xm.settlement.service.UserExpansionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 启动时将数据缓存进redis 数据库
 */
@Service
public class StartAddRedisCacheListener implements ApplicationListener<ContextRefreshedEvent> {

    private final Logger logger = LoggerFactory.getLogger(StartAddRedisCacheListener.class);


    @Autowired
    private RedisCacheUtil<UserExpansionVo> userExpansionVoRedisCache;

    @Autowired
    private RedisCacheUtil<AppBase> baseRedisCache;

    @Autowired
    private IAppBaseService appBaseService;

    @Autowired
    private UserExpansionService userExpansionService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {


        if(event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext"))
        {
            logger.info("\n\n\n_________\n\n 缓存数据start \n\n ________\n\n\n\n");

            /**---------------------------------
             *  缓存登录用户的相关信息
             *---------------------------------- */
            List<UserExpansionVo> userVoList = userExpansionService.selectUserExpansionVoList(null);
            for(UserExpansionVo userVo : userVoList ){
                userExpansionVoRedisCache.setCacheObject(RedisBeanUtils.USER_VO_MAP +"_"+ userVo.getLogin_name(),userVo);
            }

            //-- 第二部分 缓存基础参数部分
            List<AppBase> appBaseList =  appBaseService.selectListByObject(new AppBase());
            for(AppBase appBase : appBaseList ){
                baseRedisCache.setCacheObject(RedisBeanUtils.APP_BASE_MAP +"_"+appBase.getType()+"_"+appBase.getKey(),appBase);
            }
            logger.info("\n\n\n_________\n\n 缓存数据end \n\n ________\n\n\n\n ");
        }
    }
}
